package com.bestcem.xm.component.mybatis.format;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.List;

/**
 * @ClassName: String2JacksonSerializer
 * @Description: 字符串转jackson.Object 或者字符串转jackson.Array
 * @Author: chenglong.yue
 * @Date: 2022/8/19 17:53
 */
public class String2JacksonSerializer extends JsonSerializer<String> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (!ObjectUtils.isEmpty(value)) {
            if (this.isTypeJSONObject(value)) {
                TypeReference<Object> typeReference = new TypeReference<Object>() {
                };
                Object ret = objectMapper.readValue(value, typeReference);
                gen.writeObject(ret);
            } else if (this.isTypeJSONArray(value)) {
                TypeReference<List<Object>> typeReference = new TypeReference<List<Object>>() {
                };
                List<Object> ret = objectMapper.readValue(value, typeReference);
                gen.writeObject(ret);
            } else {
                throw new IOException("格式不对");
            }
        } else {
            gen.writeObject("null");
        }
    }

    private boolean isTypeJSONObject(String str) {
        boolean result = false;
        if (!ObjectUtils.isEmpty(str)) {
            str = str.trim();
            if (str.startsWith("{") && str.endsWith("}")) {
                result = true;
            }
        }
        return result;
    }

    private boolean isTypeJSONArray(String str) {
        boolean result = false;
        if (!ObjectUtils.isEmpty(str)) {
            str = str.trim();
            if (str.startsWith("[") && str.endsWith("]")) {
                result = true;
            }
        }
        return result;
    }
}
